package com.example.demo.service;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.client.AsyncRestTemplate;

@Component
public class RestCallOrchestratorServiceImpl implements RestCallOrchestratorService {

	@Autowired
	AsyncRestTemplate restTemplate;
	
	@Override
	public List<String> getmulti() throws Exception {
		List<ListenableFuture<ResponseEntity<String>>> responseFutures = new ArrayList<>();
		for (int i = 0; i < 10; i++) {
			ListenableFuture<ResponseEntity<String>> responseEntityFuture = restTemplate
					.getForEntity(new URI("http://localhost:8081/tp"), String.class);
			responseFutures.add(responseEntityFuture);
		}

		List<String> listOfResponses = new ArrayList<>();
		for (ListenableFuture<ResponseEntity<String>> future : responseFutures) {
			try {
				String respBody = future.get().getBody();
				listOfResponses.add(respBody);
			} catch (Exception ex) {
//				throw new Exception("Exception while making Rest call.", ex);
				listOfResponses.add(ex.getLocalizedMessage());
			}
		}
		return listOfResponses;
	}

}